<template>
    <div class="chart-container">
      <canvas ref="chartCanvas"></canvas>
    </div>
  </template>
  
  <script>
  import { ref, onMounted, onBeforeUnmount } from 'vue';
  import { Chart, registerables } from 'chart.js';
  
  Chart.register(...registerables);
  
  export default {
    props: {
      initialData: {  // 改为通过 initialData 统一初始化
        type: Object,
        default: () => ({
          timeLabels: [],
          voltageData: [],
          delayData: []
        })
      }
    },
    setup(props) {
      const chartCanvas = ref('null');
      let chartInstance = null;
  
      // 初始化图表
      const initChart = () => {
        const ctx = chartCanvas.value.getContext('2d');
        chartInstance = new Chart(ctx, {
          type: 'line',
          data: buildChartData(props.initialData),
          options: getChartOptions()
        });
      };
  
      // 构建图表数据 (集中管理数据结构)
      const buildChartData = (data) => {
        let datasets = [];
        for(let key in data.data) {
          let items = data.data[key].data
          let config = data.data[key].config
          if (!config.chart_show) continue // 如果该类型数据设置为不显示，则跳过
          datasets.push({
            label: `${config.name}（${config.unit}）`,
            data: items,
            borderColor: config.color,
            // backgroundColor: 'rgba(255, 99, 132, 0.1)',
            tension: 0.1,
          });
        }
        return {
          labels: data.timeLabels || [],
          datasets: datasets
        }
      };
  
      // 图表配置 (分离配置便于维护)
      const getChartOptions = () => ({
        responsive: true,
        interaction: { mode: 'index', intersect: false },
        scales: {
          x: { title: { display: true, text: '时间' } },
          // y: {
          //   type: 'linear',
          //   display: true,
          //   position: 'left',
          //   title: { display: true, text: '时延 (ms)' },
          //   grid: { drawOnChartArea: false }
          // }
        }
      });
  
      // 暴露给父组件的手动更新方法
      const handleUpdateChart = (newData) => {
        if (!chartInstance) return;
        
        // 合并新旧数据 (保留未更新的字段)
        const mergedData = {
          ...chartInstance.data,
          ...buildChartData(newData)
        };
        console.log(mergedData)
        
        chartInstance.data = mergedData;
        // 由于某些字段可能不适合用折线图表示，但是在tooltip中需要显示，因此需要在tooltip的回调函数中手动拼接
        chartInstance.options.plugins.tooltip.callbacks.afterBody = function(tooltipItems) {
            const index = tooltipItems[0].dataIndex;
            let result = []
            for (let key in newData.data) {
                if(newData.data[key].config.chart_show) continue
                let value = newData.data[key].data[index]
                if(value != null && key == 'cell_id') {
                    // cell_id特殊处理，如果value是数字的话，需要将数字转化为16进制表示
                    if(isNaN(value) == false) {
                        value = parseInt(value).toString(16).toUpperCase()
                    }
                }
                if(value != null) result.push(`${newData.data[key].config.name}: ${value}`)
            }
            return result;
        }
        chartInstance.update();
      };
  
      onMounted(initChart);
      onBeforeUnmount(() => {
        if (chartInstance) chartInstance.destroy();
      });
  
      // 暴露方法给父组件
      return { 
        chartCanvas,
        handleUpdateChart 
      };
    }
  };
  </script>